jQuery(document).ready(function($) {
   // timer
   $.metadata.setType("attr", "data");
   var metadata = $('#sheet_info').metadata();
   var total_time = parseInt(metadata.total_time);
   var times = total_time * 60;
   var timeup = false;

   var syncTimer = function() {
      var sync_url = info_sync_url;
      var data = {};
      data.jstime = times;
      data.token = $('#token').val();
      data.job_id = $('#jobid').val();

      $.ajax({
         type:"GET",
         url: sync_url,
         data:data,
         dataType: "json",
         success:function(data) {
            if (data) {
               times = data;
            }
         }
      });
   };

   var timeObj = window.setInterval(function(){
      // time's up , submit!
      if (times <= 0) {
         // check session has been recorded
         // recordSession(examSubmit);
         examSubmit();
         return;
      }

      // time text turn red!
      if (times <= 600 && timeup == false) {
         timeup = true;
         jQuery("#timeleft").addClass("timeup");
      }

      // sync time every 5 minute 
      if(times%300 == 0) {
         syncTimer();
      }
      // should record session now!
      //if (times <= 300000 && timeup == false) {
         //recordSession(false);
      //}
      var text = padDate(Math.floor(times/60))+"分"+padDate(times%60)+"秒";
      $('#timeleft').html(text);
      times --;
   }, 1000);

   // record session for ready submit
   /*function recordSession(callback) {
      $.ajax({
         type: 'GET',
         url: getsessionurl,
         dataType: 'jsonp',
         jsonp: 'keepsession',
         success: function(data) {
            jQuery('#session_id').val(data.session_id);
            if (callback) {
               callback();
            }
         }
      });
   }*/

   // exam ajax submit
   function examSubmit() {
      // Clear object first
      window.clearInterval(timeObj);

      $("#examform").ajaxSubmit({
         dataType: "json",
         beforeSubmit: function(data, form, options) {
            if (!showLoading("#examform", options, null, {button:true}))
               return false;
            $("#errormsg").hide();
         },
         success: function(data) {
            try {
               var retmsg = data;
               if (retmsg.error) {
                  $("#errormsg").jobUtil("showError", retmsg.error);
               }
               if (retmsg.success) {
                  $("#errormsg").jobUtil("showSuccess", '提交成功').fadeIn('fast');
                  window.location = retmsg.redirect;
               }
            } catch(e) {
               return false;
            }
         }
      });
   }


   // scorll to bottom, load more
   $('.exam_container').waypoint({
      offset: 'bottom-in-view',
      handler: function(direction) {
         if (direction === 'down') {
            var container = jQuery("#exam_container");
            var data = {};
            // how many questions right now
            var last_end = parseInt(jQuery('#last_end').text());
            // total count
            var total_num = parseInt(jQuery('#total_num').text());

            data.token = $('#token').val();
            data.last_end = last_end;
            data.total_num = total_num;
            if (last_end >= total_num || total_num <= 5) {
               jQuery("#paperSubmitbtn").css('display','');
               return;
            };

            // Get 5 more question's html
            jQuery.ajax({
               type:"GET",
               url: loadmore_url,
               data:data,
               dataType: "html",
               beforeSend: function(xhr){
                  jQuery("#loadmorequstion").css('display','');
               }, success:function(data) {
                  if (data) {
                     container.append("<div id='append_div_"+last_end+"' ></div>");
                     jQuery('#append_div_'+last_end).html(data);
                     jQuery('#last_end').text(parseInt(last_end)+5);
                     jQuery("#loadmorequstion").css('display','none');
                     if (last_end+5 >= total_num || total_num <= 5) {
                        jQuery("#paperSubmitbtn").css('display','');
                     };
                  }
                  // Enable the waypoint again to find the new container area bottom
                  $('.exam_container').waypoint('enable');
               }
            });
         };
      }
   });

   // stick top bar
   $('.sticky_element').waypoint('sticky');

   // form action
   jQuery("#examform").validate({
      submitHandler: function(form) {
         examSubmit();
         // check session has been recorded
         //recordSession(examSubmit);
      },
      errorElement: "div",
      errorPlacement: function (error, element) {
         error.appendTo(element.parent().parent());
      }
   });

   $("#paperSubmitbtn").prop('disabled',false);
});
